import 'package:flutter/material.dart';
import 'package:hxdj/common/base_page/my_loading_page.dart';
import 'package:hxdj/common/components/banner.dart';
import 'package:hxdj/common/components/my_app_bottom.dart';
import 'package:hxdj/common/components/my_picture_preview.dart';
import 'package:hxdj/common/components/my_statistic.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/components/underline_tab.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/home/project_details/project_details_viewmodel.dart';
import 'package:hxdj/mine/member_center/member_center_page.dart';

//套餐详情
class PackageDetailPage extends StatefulWidget {
  static String routeName = "/PackageDetail";

  final String? tId, gId;

  const PackageDetailPage({super.key, required this.tId, required this.gId});

  @override
  State<PackageDetailPage> createState() => _PackageDetailPageState();
}

class _PackageDetailPageState extends State<PackageDetailPage> with TickerProviderStateMixin {
  late ProjectDetailsViewModel viewModel;

  late TabController _tabController;

  List<String> tabs = ["服务说明", "服务禁忌", "下单须知"];

  late int selectIndex = 0;
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabs.length, vsync: this);
  }

  _buildBottomWidget() {
    // //获取用户信息
    // MyGlobalViewModel globalViewModel = Provider.of<MyGlobalViewModel>(context, listen: false);
    // UserModel? userModel = globalViewModel.userModel;
    //是否是会员
    bool isVip = viewModel.detailModel.isVip == 1;

    return SafeArea(
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            decoration: const BoxDecoration(color: Colors.white, boxShadow: <BoxShadow>[
              BoxShadow(
                color: Color.fromRGBO(0, 0, 0, 0.05),
                offset: Offset(0.0, -13),
                blurRadius: 12.0,
                spreadRadius: -9.0,
              )
            ]),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.only(top: 10.h, left: 30.w, right: 30.w, bottom: 10.h),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: MyTapWidget(
                          onTap: () {
                            if (isVip) {
                              //去支付
                              viewModel.createOrder();
                            } else {
                              //去会员中心
                              NavigatorUtils.push(context, MemberCenterPage.routeName).then((value) {
                                viewModel.requestData(tmId: widget.tId ?? "", gmId: widget.gId ?? "");
                              });
                            }
                          },
                          child: Container(
                            alignment: Alignment.center,
                            margin: EdgeInsets.only(right: 10.w),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20.w),
                              gradient: const LinearGradient(
                                colors: [Color.fromRGBO(60, 54, 54, 1), Color.fromRGBO(29, 29, 28, 1)],
                                begin: Alignment.centerLeft,
                                end: Alignment.centerRight,
                              ),
                            ),
                            padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.h),
                            child: MyText("会员购¥${viewModel.detailModel.goodsDiscountPrice}",
                                color: MyColours.colorF0D3BB, fontSize: 14.sp),
                          ),
                        ),
                      ),
                      SizedBox(width: isVip ? 0 : 10.w),
                      isVip
                          ? Container()
                          : Expanded(
                              flex: 1,
                              child: MyTapWidget(
                                  onTap: () {
                                    //去支付
                                    viewModel.createOrder();
                                  },
                                  child: MyBorder(
                                    backgroundColor: MyColours.appMain,
                                    color: MyColours.appMain,
                                    radius: 20.w,
                                    child: Container(
                                      alignment: Alignment.center,
                                      padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.h),
                                      child: Text(
                                        "¥${viewModel.detailModel.price ?? "0"}",
                                        style: TextStyle(
                                            color: MyColours.materialBg, fontSize: 14.sp, fontWeight: FontWeight.w700),
                                      ),
                                    ),
                                  )),
                            ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Positioned(
              left: 61.w,
              top: -33.w,
              child: isVip
                  ? Container()
                  : Container(
                      width: 102, // 可以根据需要设置容器的宽度
                      height: 45, // 可以根据需要设置容器的高度
                      decoration: const BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/ic_vip_tip.png'), // 使用 AssetImage 加载本地图片资源
                          fit: BoxFit.cover, // 图片填充方式，cover 表示等比例填充整个容器
                        ),
                      ),
                      child: Container(
                        padding: const EdgeInsets.only(top: 7),
                        child: Text("开通VIP再下单\n本单最高可省${viewModel.detailModel.goodsHighDiscountPrice}元",
                            textAlign: TextAlign.center,
                            style: TextStyle(color: MyColours.materialBg, fontSize: 8.sp, fontWeight: FontWeight.w600)),
                      ),
                    )),
        ],
      ),
    );
  }

  //详情
  _buildProjectDetail() {
    return Container(
        margin: EdgeInsets.all(15.w),
        child: MyBorder(
            decoration: MyBorder.defaultDecoration,
            radius: 10,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  //金额
                  Container(
                    child: MyStatisticViewModel(
                      statistic: num.parse(viewModel.detailModel.price ?? "0"),
                      statisticTS:
                          TextStyle(fontSize: 18.sp, color: MyColours.colorFF4414, fontWeight: FontWeight.w700),
                      withName: '¥' "",
                      withNameTS: TextStyle(fontSize: 15.sp, color: MyColours.colorFF4414, fontWeight: FontWeight.w700),
                      statisticDecimalTS: TextStyle(color: MyColours.colorFF4414, fontSize: 15.sp),
                      prefix: '',
                      suffix: '',
                      isCurrency: false,
                      toStringAsFixed: 0,
                    ).toRichText,
                  ),

                  //title
                  Padding(
                    padding: EdgeInsets.only(top: 5.w, bottom: 5.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        MyText(viewModel.detailModel.title ?? "",
                            fontSize: 14.sp, fontWeight: FontWeight.bold, color: MyColours.text),
                        MyText("30天${viewModel.detailModel.salesStr ?? ""}",
                            fontSize: 9.sp, fontWeight: FontWeight.bold, color: MyColours.textGrayA),
                      ],
                    ),
                  ),
                  MyText("${viewModel.detailModel.serviceDurationStr}", fontSize: 12.sp, color: MyColours.textGray),
                ],
              ),
            )));
  }

  List<Widget> _buildTabWidget() {
    List<Widget> tabsWidget = [];

    tabsWidget = tabs.map((e) => MyText(e)).toList();
    return tabsWidget;
  }

  _buildDescribe() {
    String desc = viewModel.detailModel.desc ?? "";
    List<String> descList = desc.split("\n");

    List<Map<String, dynamic>> descDetailList = [];
    for (String element in descList) {
      element = element.replaceAll("【", "");

      List<String> elementList = element.split("】");

      Map<String, dynamic> map = {};
      map[elementList.first] = elementList.last;
      descDetailList.add(map);
    }

    String goodsRemindText = viewModel.detailModel.goodsRemindText ?? "";
    List<Map<String, dynamic>> goodsRemindlList = [];

    List<String> goodsRemindTextList = goodsRemindText.split("\n");
    for (String element in goodsRemindTextList) {
      Map<String, dynamic> map = {};
      map[""] = element;
      goodsRemindlList.add(map);
    }

    List<Map<String, dynamic>> contentList = [
      {
        "服务说明": [
          {"按摩部位:": "背部、颈部、肩部背部、颈部、肩部背部;"},
          {"服务时长:": "120分钟;"},
          {"适用人群:": "亚健康群体、主要针对压力山大人群;"},
          {"功能介绍:": "根据中医原理，通过问、切配以揉、拨、功效介绍点、压穴位的手法，从而达到活血化;"},
        ]
      },
      {
        "服务禁忌": [
          {"": "饭后半小时之内不宜进行按摩"},
          {"": "骨折复位稳定，开放性骨折人体;"},
          {"": "妇女月经期间和壬辰期间不宜进行腹部、腰骶部按摩;"},
          {"": "感染性疾病，如骨结核、骨髓炎禁止按摩;"},
          {"": "皮肤病，皮肤破损者如脓肿蜂窝组织炎烧，伤烫伤疱疹摩;"},
          {"": "其他严重疾病或者诊断不明的较严重疾病禁止按摩;"},
        ]
      },
      {
        "下单须知": [
          {"服务质量": "本平台服务由第三方合作商提供，用户有权监督技师的服务质量，如服务质量不达标，请向平台进行反馈；如技师未在约定情况下早退或服务质量不达标，用户有权向平台进行申诉"},
          {
            "取消订单":
                "用户预约下单后，技师时间将被锁定，为了保障技师的权益，不支持取消订单（服务商或技师原因造成订单无法完成除外);技师到达后如无法联系到用户等用户因素导致该订单无法继续，该订单视为无法取消订单;因技师或服务商导致订单无法正常完成的，一律支持取消订单，不扣任何费用;结束订单均视为该订单正常完成，订单完成后均不支持取消;"
          },
          {"温馨提示": "保健理疗师也是广大劳动群众中的一份子，所有用户必须给予尊重。"},
        ]
      },
    ];

    Map<String, dynamic> contentMap = contentList[selectIndex];

    List valueList = contentMap[contentMap.keys.first];
    return Container(
        margin: EdgeInsets.only(left: 15.w, right: 15.w, bottom: 15.w),
        child: Column(
          children: [
            Container(
              height: 45.w,
              decoration: BoxDecoration(
                  color: MyColours.appMain,
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(11.0.w), topRight: Radius.circular(11.0.w))),
              child: TabBar(
                  controller: _tabController,
                  labelColor: MyColours.materialBg,
                  unselectedLabelColor: MyColours.materialBg,
                  dividerColor: Colors.transparent,
                  labelStyle: TextStyle(fontSize: 17.sp, fontWeight: FontWeight.w600),
                  unselectedLabelStyle: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.normal),
                  indicator: const CAUnderlineTabIndicator(
                      indicatorBottom: 5,
                      indicatorWidth: 30,
                      isRound: true,
                      borderSide: BorderSide(
                        width: 3,
                        color: MyColours.materialBg,
                      )),
                  indicatorPadding: EdgeInsets.zero,
                  tabs: _buildTabWidget(),
                  onTap: (value) => setState(() {
                        selectIndex = value;
                      })
                  // tabs: _buildTabWidget(),
                  ),
            ),

            //内容
            Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      offset: const Offset(0, 2),
                      blurRadius: 12,
                      spreadRadius: 0,
                    )
                  ],
                ),
                child: Stack(
                  children: [
                    selectIndex == 2
                        ? Positioned(
                            bottom: 0,
                            left: 0,
                            right: 0,
                            child: Container(
                                padding: EdgeInsets.only(left: 22.w, right: 22.w, top: 58.h, bottom: 13.h),
                                margin: EdgeInsets.symmetric(horizontal: 12.5.w, vertical: 16.w),
                                decoration: BoxDecoration(
                                  color: MyColours.appMain.withOpacity(0.4),
                                  borderRadius: BorderRadius.circular(11.w),
                                ),
                                child: Column(
                                  children: [
                                    Text(
                                      "平台仅提供正规绿色按摩服务，如用户、商家及技师存在 涉及黄赌毒等违法犯罪活动，我们将坚决依法处理。",
                                      maxLines: 2,
                                      style: TextStyle(
                                          fontSize: 11.sp, color: MyColours.appMain, fontWeight: FontWeight.bold),
                                    ),
                                  ],
                                )),
                          )
                        : Container(),
                    Container(
                      margin: EdgeInsets.only(
                          left: 12.5.w, right: 12.5.w, top: 16.h, bottom: selectIndex == 2 ? 63.h : 16.h),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border.all(color: MyColours.line, width: 1),
                        borderRadius: BorderRadius.circular(11.w),
                      ),
                      child: Container(
                        padding: EdgeInsets.fromLTRB(15.w, 15.w, 20.w, 0),
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: valueList.map((e) {
                              Map<String, dynamic> resultMap = Map<String, dynamic>.from(e);

                              return Container(
                                padding: EdgeInsets.only(bottom: 15.w),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Container(
                                      padding: EdgeInsets.only(top: 5.w),
                                      child: MyBorder(
                                        backgroundColor: MyColours.appMain,
                                        radius: 2.5.w,
                                        child: SizedBox(
                                          width: 5.w,
                                          height: 5.w,
                                        ),
                                      ),
                                    ),
                                    CommonPlugin.isEmpty(resultMap.keys.first)
                                        ? Container(padding: EdgeInsets.only(left: 5.w))
                                        : Container(
                                            padding: EdgeInsets.only(left: 5.w, right: 10.w),
                                            child: MyText(resultMap.keys.first,
                                                color: MyColours.appMain,
                                                fontSize: 11.5.sp,
                                                fontWeight: FontWeight.bold),
                                          ),

                                    // 文本会自动换行，如果容器宽度不足以容纳整个文本
                                    Expanded(
                                      child: Text(
                                        resultMap.values.first,
                                        style: TextStyle(color: MyColours.text, fontSize: 11.sp),
                                        softWrap: true, // 允许文本换行，但通常不是必需的，因为 Text widget 默认会处理换行
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            }).toList()),
                      ),
                    ),
                  ],
                ))
          ],
        ));
  }

  _buildBody() {
    switch (viewModel.state) {
      case ViewState.loading:
        return const Scaffold(appBar: MyAppBar(title: "项目详情"), body: MyLoadingWidget());
      default:
        List<String>? imgs = viewModel.detailModel.coverImg?.split(",") ?? [""];
        imgs.removeWhere((element) => (element.endsWith("mp4") || element.endsWith("MOV")));

        return Scaffold(
            appBar: const MyAppBar(title: "项目详情"),
            bottomNavigationBar: _buildBottomWidget(),
            body: SingleChildScrollView(
              child: Stack(
                children: [
                  Column(
                    children: [
                      MyBannerView(imgs, select: (int index) {
                        NavigatorUtils.pushParams(context, MyPicturePreviewPage.routeName,
                            params: {"index": index, "imgUrls": imgs, "heroTag": imgs[index]});
                      }),
                      // Your existing code here
                      _buildProjectDetail(),
                      _buildDescribe(),
                      MyAppBottom.buildBottom(),
                    ],
                  ),
                ],
              ),
            ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return BasePage<ProjectDetailsViewModel>(
        onModelReady: (model) {
          // 页面初始化完成后的回调
          viewModel = model;

          viewModel.requestData(tmId: widget.tId ?? "", gmId: widget.gId ?? "");
        },
        viewModel: ProjectDetailsViewModel(),
        builder: (BuildContext context, ProjectDetailsViewModel? model, Widget? child) {
          return _buildBody();
        });
  }
}
